package org.simpleframework.mvc;

import org.simpleframework.aop.AspectWeaver;
import org.simpleframework.core.BeanContainer;
import org.simpleframework.inject.DependencyInjector;
import org.simpleframework.mvc.processor.RequestProcessor;
import org.simpleframework.mvc.processor.impl.ControllerRequestProcessor;
import org.simpleframework.mvc.processor.impl.JspRequestProcessor;
import org.simpleframework.mvc.processor.impl.PreRequestProcessor;
import org.simpleframework.mvc.processor.impl.StaticResourceRequestProcessor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 该servlet用来接受前端传递过来的所有请求,并指派给RequestProcessorChain去完成.
 *
 * @author: Oliver
 * @time: 2020/12/28/21:58
 */
@WebServlet("/*")
public class DispatcherServlet extends HttpServlet {

    private List<RequestProcessor> processors = new ArrayList<>(4);

    /**
     * 初始化操作 完成对常驻内存对象的初始化 包括对请求处理器的实例化.
     *
     * @throws ServletException
     */
    @Override
    public void init() throws ServletException {
        // 初始化容器
        BeanContainer beanContainer = BeanContainer.getInstance();
        beanContainer.loadBeans("com.wyp");
        new AspectWeaver().doAop();
        new DependencyInjector().doIoc();
        //2.初始化请求处理器责任链
        processors.add(new PreRequestProcessor());
        processors.add(new StaticResourceRequestProcessor(getServletContext()));
        processors.add(new JspRequestProcessor(getServletContext()));
        processors.add(new ControllerRequestProcessor());
    }

    /**
     * 主要是将任务分配给RequestProcessorChain去完成  请求处理器的调用, 返回结果的收集.都交由他来完成
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 初始化 RequestProcessorChain
        RequestProcessorChain chain = new RequestProcessorChain(processors.iterator(), req, resp);
        // 使用责任链模式进行将请求交由RequestProcessor进行处理.
        chain.doRequestProcessor();
        // 对处理结果进行渲染
        chain.doRender();
    }

}
